﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;

namespace WebComTest.WebUI.Models.RequestManagers
{
    public class JsonRequest
    {
        private string url { get; set; }

        public JsonRequest(string url)
        {
            this.url = url;
        }

        public string Exec(string jsonMessage)
        {
            string jsonResult;

            HttpWebRequest webRequest = GetWebRequestHeader(this.url);

            using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
            {
                streamWriter.Write(jsonMessage);
            }

            using (WebResponse webResponse = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
                {
                    jsonResult = rd.ReadToEnd();
                }
            }

            return jsonResult;
        }

        private HttpWebRequest GetWebRequestHeader(string url)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.ContentType = "text/json";
            webRequest.Method = "POST";
            return webRequest;
        }
    }
}